package com.banban.user.util;
import com.alibaba.fastjson.JSON;
import com.banban.user.config.DeepSeekConfig;
import com.banban.user.domain.DeepSeekRequestModel;
import okhttp3.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

@Component
public class DeepSeekSendMessage {
    private final OkHttpClient client;

    @Autowired
    private DeepSeekConfig deepSeekConfig;

    public DeepSeekSendMessage() {
        // 设置超时时间
        this.client = new OkHttpClient.Builder()
                .connectTimeout(10, java.util.concurrent.TimeUnit.SECONDS) // 连接超时时间
                .writeTimeout(600, java.util.concurrent.TimeUnit.SECONDS)  // 写入超时时间
                .readTimeout(600, java.util.concurrent.TimeUnit.SECONDS)   // 读取超时时间
                .build();
    }

    public String getResponse(String prompt, String systemMessage) throws IOException {
        // 构建消息列表
        List<DeepSeekRequestModel.Message> messages = new ArrayList<>();

        // 如果有 system 消息，先添加 system 消息
        if (systemMessage != null && !systemMessage.trim().isEmpty()) {
            messages.add(DeepSeekRequestModel.Message.builder()
                    .role("system")
                    .content(systemMessage)
                    .build());
        }

        // 添加 user 消息
        messages.add(DeepSeekRequestModel.Message.builder()
                .role("user")
                .content(prompt)
                .build());

        // 构建请求体
        DeepSeekRequestModel deepSeekRequest = DeepSeekRequestModel.builder()
                .model("deepseek-chat")
                .messages(messages)
                .build();

        String jsonBody = JSON.toJSONString(deepSeekRequest);

        // 创建 HTTP 请求
        Request httpRequest = new Request.Builder()
                .url(deepSeekConfig.getApiUrl())
                .post(RequestBody.Companion.create(jsonBody, MediaType.parse("application/json")))
                .addHeader("Authorization", "Bearer " + deepSeekConfig.getApiKey())
                .build();

        // 发送请求并处理响应
        try (Response response = client.newCall(httpRequest).execute()) {
            if (response.isSuccessful() && response.body() != null) {
                String responseBody = response.body().string();
                // 解析响应体，提取模型回复内容
                return extractModelResponse(responseBody);
            } else {
                throw new RuntimeException("API 请求失败，状态码：" + response.code());
            }
        }
    }

    private String extractModelResponse(String responseBody) {
        // 假设响应体是一个 JSON 格式，包含一个字段 "choices"，其中包含模型的回复内容
        try {
            com.alibaba.fastjson.JSONObject jsonResponse = JSON.parseObject(responseBody);
            if (jsonResponse.containsKey("choices") && jsonResponse.getJSONArray("choices").size() > 0) {
                com.alibaba.fastjson.JSONObject choice = jsonResponse.getJSONArray("choices").getJSONObject(0);
                if (choice.containsKey("message") && choice.getJSONObject("message").containsKey("content")) {
                    return choice.getJSONObject("message").getString("content");
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "无法解析模型回复内容";
    }
}